//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;

namespace OpenLS.Spreadsheet.StandardAddIn.Statistics
{
    internal class SimpleRegression
    {
        private readonly double _intercept;


        private readonly int count;
        private readonly double sumXX;
        private readonly double sumXY;
        private readonly double sumYY;
        private readonly double xMean;
        private readonly double yMean;
        public double RSQ
        {
            get
            {
                double den = sumXX*sumYY;
                double num = sumXY;
                return num*num/den;
            }
        }

        public SimpleRegression(IList<double> xx, IList<double> yy, RegressionType type)
        {
            if (type == RegressionType.WithoutIntercept)
            {
                xMean = 0;
                yMean = 0;
            }
            else
            {
                xMean = Statistician.Mean(xx);
                yMean = Statistician.Mean(yy);
            }
            count = xx.Count;
            for (int i = 0; i < count; i++)
            {
                double dx = xx[i] - xMean;
                double dy = yy[i] - yMean;
                sumXX += dx*dx;
                sumYY += dy*dy;
                sumXY += dx*dy;
            }
            if (type == RegressionType.WithIntercept)
                _intercept = yMean - Slope*xMean;
        }

        public double Intercept
        {
            get { return _intercept; }
        }

        public double Slope
        {
            get
            {
                if (count < 2)
                    return Double.NaN;
                return sumXY/sumXX;
            }
        }


        internal double Correlation
        {
            get { return sumXY/Math.Sqrt(sumXX*sumYY); }
        }
    }
}